package com.gomore.opple.module.addbankcard;

import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventReleshMine;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.rest.applybill.TOBankBindEntity;
import com.gomore.opple.rest.applybill.TOCommAuthEntity;
import com.gomore.opple.utils.DialogUtils;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/**
 * Created by robot
 */
public class AddBankCardFragment extends BaseFragment implements AddBankCardContract.View {

    @Bind(R.id.back)
    LinearLayout back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.first_page)
    LinearLayout first_page;
    @Bind(R.id.card_owner_name)
    EditText card_owner_name;
    @Bind(R.id.card_number)
    EditText card_number;
    @Bind(R.id.identify_number)
    EditText identify_number;
    @Bind(R.id.mobile_number)
    EditText mobile_number;
    @Bind(R.id.next)
    TextView next;
    @Bind(R.id.second_page)
    LinearLayout second_page;
    @Bind(R.id.bank_name)
    TextView bank_name;
    @Bind(R.id.phone_eight)
    TextView phone_eight;
    @Bind(R.id.get_message)
    TextView get_message;
    @Bind(R.id.message)
    EditText message;
    @Bind(R.id.confirm)
    TextView confirm;

    private AddBankCardContract.Presenter mPresenter;
    private String bankNumber;
    private String cardType;
    //短信验证码
    private TimerTask timerTask;
    private int recordTime;

    public static AddBankCardFragment getInstance() {
        return new AddBankCardFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_add_bank_card;
    }

    @Override
    protected void initalizeData() {

    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
        MyWatcher myWatcher = new MyWatcher();
        card_number.addTextChangedListener(myWatcher);
    }


    @Override
    public void setPresenter(AddBankCardContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void showSecondPage() {
        first_page.setVisibility(View.GONE);
        second_page.setVisibility(View.VISIBLE);
        title.setText(getResources().getString(R.string.add_bank_card));
        if (getBankName(bankNumber) != null) {
            cardType = getBankName(bankNumber);
        } else {
            cardType = "未获取到该卡的类型";
        }
        bank_name.setText(cardType);
        String mobile = mobile_number.getText().toString().trim();
        String mobile1 = mobile.substring(0, 3);
        String mobile2 = mobile.substring(mobile.length() - 4, mobile.length());
        phone_eight.setText("请输入改手机号" + mobile1 + "****" + mobile2 + "收到的验证码");
    }

    @Override
    public void finishActivity() {
        stopTimer();
        EventReleshMine eventReleshMine = new EventReleshMine();
        eventReleshMine.setReflash(true);
        EventBus.getDefault().post(eventReleshMine);
        getActivity().finish();
    }

    @OnClick({R.id.back, R.id.next, R.id.get_message, R.id.confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                showPage();
                break;
            case R.id.next:
                submitBankCardMessage();
                break;
            case R.id.get_message:
                mPresenter.sendCode(mobile_number.getText().toString().trim());
                //开启计时器
                starTimer();
                break;
            case R.id.confirm:
                bandCard();
                break;
        }
    }

    //提交银行卡信息
    private void submitBankCardMessage() {
        if (TextUtils.isEmpty(card_owner_name.getText().toString().trim())) {
            showMessage("请输入持卡人");
            return;
        }
        if (TextUtils.isEmpty(card_number.getText().toString().trim())) {
            showMessage("请输入银行卡号");
            return;
        }
        if (TextUtils.isEmpty(identify_number.getText().toString().trim())) {
            showMessage("请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(mobile_number.getText().toString().trim())) {
            showMessage("请输入电话号码");
            return;
        }
        if (!isPhoneNumberValid(mobile_number.getText().toString().trim())) {
            showMessage("请输入正确的电话号码");
            return;
        }
        //去除字符串中的空格、回车、换行符、制表符
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(card_number.getText().toString());
        bankNumber = m.replaceAll("");
        TOCommAuthEntity toCommAuthEntity = new TOCommAuthEntity();
        toCommAuthEntity.setAccountName(card_owner_name.getText().toString().trim());
        toCommAuthEntity.setBankAccount(bankNumber);
        toCommAuthEntity.setIdentityCode(identify_number.getText().toString().trim());
        toCommAuthEntity.setPhoneNumber(mobile_number.getText().toString().trim());
        mPresenter.commAuth(toCommAuthEntity);
    }

    //绑定银行卡
    private void bandCard() {
        if (TextUtils.isEmpty(message.getText().toString().trim())) {
            showMessage("请输入验证码");
            return;
        }
        TOBankBindEntity toBankBindEntity = new TOBankBindEntity();
        toBankBindEntity.setAccountName(card_owner_name.getText().toString().trim());
        toBankBindEntity.setBankAccount(bankNumber);
        toBankBindEntity.setIdentityCode(identify_number.getText().toString().trim());
        toBankBindEntity.setPhoneNumber(mobile_number.getText().toString().trim());
        toBankBindEntity.setSmsCode(message.getText().toString().trim());
        toBankBindEntity.setBankCardType(cardType);
        mPresenter.bind(toBankBindEntity);
    }

    //判断是否为电话号码
    private boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        String expression = "((^(13|14|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    //获取银行名字
    private String getBankName(String cardnumber) {
        String headcardnumber = cardnumber.substring(0, 6);
        String bankName = GlobalConstant.BankName().get(headcardnumber);
        return bankName;
    }

    //返回按钮
    public void showPage() {
        //关闭计时器
        stopTimer();
        if (first_page.getVisibility() == View.GONE) {
            title.setText(getResources().getString(R.string.bank_card_is_true));
            first_page.setVisibility(View.VISIBLE);
            second_page.setVisibility(View.GONE);
        } else if (first_page.getVisibility() == View.VISIBLE) {
            getActivity().finish();
        }
    }

    class MyWatcher implements TextWatcher {
        int beforeTextLength = 0;
        int onTextLength = 0;
        boolean isChanged = false;
        int location = 0;
        // 记录光标的位置
        private char[] tempChar;
        private StringBuffer buffer = new StringBuffer();
        int konggeNumberB = 0;

        @Override
        public void onTextChanged(CharSequence text, int start, int before, int count) {
            // TODO Auto-generated method stub
            onTextLength = text.length();
            //银行卡空格
            buffer.append(text.toString());
            if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                isChanged = false;
                return;
            }
            isChanged = true;
        }

        @Override
        public void beforeTextChanged(CharSequence text, int start, int count, int after) {
            // TODO Auto-generated method stub
            beforeTextLength = text.length();
            if (buffer.length() > 0) {
                buffer.delete(0, buffer.length());
            }
            konggeNumberB = 0;
            for (int i = 0; i < text.length(); i++) {
                if (text.charAt(i) == ' ') {
                    konggeNumberB++;
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            // TODO Auto-generated method stub
            if (isChanged) {
                location = card_number.getSelectionEnd();
                int index = 0;
                while (index < buffer.length()) {
                    if (buffer.charAt(index) == ' ') {
                        buffer.deleteCharAt(index);
                    } else {
                        index++;
                    }
                }
                index = 0;
                int konggeNumberC = 0;
                while (index < buffer.length()) {
                    if ((index + 1) % 5 == 0) {
                        // if ((index == 4 || index == 9 || index == 14 || index
                        // == 19)) {
                        buffer.insert(index, ' ');
                        konggeNumberC++;
                    }
                    index++;
                }

                if (konggeNumberC > konggeNumberB) {
                    location += (konggeNumberC - konggeNumberB);
                }
                tempChar = new char[buffer.length()];
                buffer.getChars(0, buffer.length(), tempChar, 0);
                String str = buffer.toString();
                if (location > str.length()) {
                    location = str.length();
                } else if (location < 0) {
                    location = 0;
                }
                card_number.setText(str);
                Editable etable = card_number.getText();
                Selection.setSelection(etable, location);
                isChanged = false;
            }
        }
    }

    /**
     * 开启计时
     */
    private void starTimer() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recordTime++;
                        if (recordTime == 60) {
                            if (timerTask != null) {
                                timerTask.cancel();
                            }
                            get_message.setText(getActivity().getResources().getString(R.string.checkCode_send));
                        } else {
                            int have = 60 - recordTime;
                            get_message.setText("( " + have + "S )");
                        }
                    }
                });
            }
        };
        Timer recordTimer = new Timer(true);
        recordTimer.schedule(timerTask, 0, 1000);
    }

    /**
     * 关闭计时器
     */
    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        get_message.setText(getActivity().getResources().getString(R.string.checkCode_send));
    }
}